
package com.wwy.monitor.service.impl;

import java.util.ArrayList;
import java.util.List;

import com.alibaba.buc.api.HavanaQueryService;
import com.alibaba.buc.api.model.SimpleUser;
import com.alibaba.buc.api.ucweb.model.ResultAsRpc;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.ihr.amdplatform.common.util.AmdpResponseUtil;
import com.alibaba.ihr.amdplatform.service.api.AmdpDataQueryService;
import com.alibaba.ihr.amdplatform.service.dto.QueryResultDTO;
import com.alibaba.ihr.amdplatform.service.dto.ResultDTO;
import com.alibaba.ihr.amdplatform.service.param.AuthParam;
import com.alibaba.ihr.amdplatform.service.param.DataQueryParam;
import com.alibaba.ihr.amdplatform.service.param.FilterField;
import com.alibaba.xxpt.gateway.shared.client.http.ExecutableClient;
import com.alibaba.xxpt.gateway.shared.client.http.PostClient;
import com.wwy.monitor.amdp.dto.Combine1266;
import com.wwy.monitor.service.UserService;
import com.wwy.monitor.util.UserUtils;
import com.autonavi.acis.system.model.User;
import com.taobao.hsf.app.spring.util.annotation.HSFConsumer;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * @Descriptionï¼
 * @Author: zhenfei.gz
 * @Date: 2019/11/7 9:03 PM
 */
@Service
public class UserSerciveImpl implements UserService {
    //public static final String BUC_KEYWORD_URL = "/rpc/enhancedUserQuery/findUsers/byKeyWord.json";
    @Autowired
    private ExecutableClient executableClient;
    @Autowired
    private AuthParam authParam;
    @Autowired
    private AmdpDataQueryService amdpDataQueryService;
    @HSFConsumer(serviceVersion = "${buc.havana.version}", serviceGroup = "${buc.havana.group}")
    private HavanaQueryService havanaQueryService;
    @Value("${amdp.combineId}")
    private String combineId;
    private static final int suggestSize = 10;

    @Override
    public List<User> findByKeywordAndSize(String keyword, Integer size) throws Exception {
        List<User> users = findUserByBUC(keyword, size);
        return users;
    }

    public List<User> findUserByBUC(String keyword, Integer size) throws Exception {
        List<User> users = new ArrayList<>();
/*PostClient postClient = executableClient.newPostClient(BUC_KEYWORD_URL);
postClient.addParameter("keyWord", keyword);
postClient.addParameter("searchType", "name");
postClient.addParameter("available", "T");
postClient.addParameter("hrStatus", "A");
postClient.addParameter("page", "1");
postClient.addParameter("sizePerPage", String.valueOf(size == null ? suggestSize : size));
String response = postClient.post();
JSONObject enhancedUsers = JSON.parseObject(response);
JSONObject content = enhancedUsers.getJSONObject("content");
if (content != null) {
JSONArray items = content.getJSONArray("items");
if (items != null) {
for (Object item : items) {
if (item instanceof JSONObject) {
JSONObject enhancedUser = (JSONObject)item;
User user = new User();
user.setBucId(enhancedUser.getLong("id"));
user.setEmpId(enhancedUser.getString("empId"));
user.setNickNameCn(enhancedUser.getString("nickNameCn"));
user.setRealNameCn(enhancedUser.getString("lastName"));
user.setEmail(enhancedUser.getString("emailAddr"));
user.setDepDesc(enhancedUser.getString("depDesc"));
users.add(user);}
}}
}*/
//2.èåè¯·æ±参数å°è£
        DataQueryParam queryParam = new DataQueryParam();
//2.1 è®¾ç½®èåid
        queryParam.setCombineId(Long.valueOf(combineId));
        List<FilterField> filterFieldList = new ArrayList<FilterField>();
        FilterField searchKeyField = new FilterField();
        searchKeyField.setName("searchKey");
        searchKeyField.setValue(keyword);
        filterFieldList.add(searchKeyField);
        FilterField pageSizeField = new FilterField();
        pageSizeField.setName("pageSize");
        pageSizeField.setValue(suggestSize);
        filterFieldList.add(pageSizeField);
        queryParam.setFilterFieldList(filterFieldList);
//3 åèµ·è°ç¨ï¼è·åç»æ
        ResultDTO<QueryResultDTO> resultDTO = amdpDataQueryService.queryDataSet(authParam, queryParam);
        List<Combine1266> combine1266 = AmdpResponseUtil.convertCombineResultToBeanList(resultDTO, Combine1266.class);
        if (CollectionUtils.isNotEmpty(combine1266)) {
            querEmployeeInfos(users, combine1266);
            queryUsersBucId(users);
        }
        return users;
    }

    /**
     * è°ç¨bucæ¥å£è·åbucId
     *
     * @param users
     */
    private void queryUsersBucId(List<User> users) {
//æ ¹æ®å·¥å·æ¥è¯¢userId
        ResultAsRpc<SimpleUser> simpleUser = null;
        SimpleUser contentSimpleUser = null;
        for (User item : users) {
            simpleUser = havanaQueryService.getSimpleUserByEmpId(item.getEmpId());
            contentSimpleUser = simpleUser.getContent();
            item.setBucId(null == contentSimpleUser.getUserId() ? null :
                    Long.valueOf(contentSimpleUser.getUserId()));
        }
    }

    /**
     * è·åç¨æ·ä¿¡æ¯
     *
     * @param users
     * @param combine1266
     */
    private void querEmployeeInfos(List<User> users, List<Combine1266> combine1266) {
        Combine1266.EmpEmployee empEmployee = null;
        Combine1266.OrgDept orgDept = null;
        User user = null;
        for (Combine1266 item : combine1266) {
            empEmployee = item.getEmpEmployee();
            orgDept = item.getOrgDept();
            user = new User();
            user.setEmpId(UserUtils.empIdFilter(empEmployee.getWorkNo()));
            user.setNickNameCn(empEmployee.getNickName());
            user.setRealNameCn(empEmployee.getName());
            user.setEmail(empEmployee.getBuMail());
            user.setDepDesc(orgDept.getDeptName());
            users.add(user);
        }
    }
}